package com.zhu.salesmanagement.utils;

import java.text.SimpleDateFormat;
import java.util.Date;

import android.content.ContentValues;
import android.content.Context;
import android.content.pm.PackageManager.NameNotFoundException;
import android.database.Cursor;
import android.net.Uri;
import android.util.Log;

import com.zhu.salesmanagement.VisitTaskListActivity;
import com.zhu.salesmanagement.common.Actions;
import com.zhu.salesmanagement.models.VerifyUserResult;
import com.zhu.salesmanagement.models.VisitTaskInfo;
import com.zhu.salesmanagement.provider.SalesSettings;

public class Util {
    static double DEF_PI = 3.14159265359; // PI
	static double DEF_2PI= 6.28318530712; // 2*PI
	static double DEF_PI180= 0.01745329252; // PI/180.0
	static double DEF_R =6370693.5; // radius of earth

    public static VerifyUserResult mVerifyUserResult = null;
    public static boolean isFirst = false;

    public static boolean saveStoresCheckinInfo(Context context, VisitTaskInfo visitTaskInfo, double lat, double lng, boolean isSaveType){
        try{
            ContentValues values = new ContentValues();
            values.put(SalesSettings.VisitedStoresColumns.STOREID, visitTaskInfo.id);
            values.put(SalesSettings.VisitedStoresColumns.CHECKIN_LAT, lat);
            values.put(SalesSettings.VisitedStoresColumns.CHECKIN_LNG, lng);
            values.put(SalesSettings.VisitedStoresColumns.CHECKIN_TIME, visitTaskInfo.mCheckinTime);

            if(Actions.DEBUG){
                Log.e("zhu","checkin id="+visitTaskInfo.mDbId);
            }
            if(visitTaskInfo.mDbId == -1){
                if(isSaveType){
                    values.put(SalesSettings.VisitedStoresColumns.VISITCATEGOR, visitTaskInfo.type);
                }
                Uri uri = context.getContentResolver().insert(SalesSettings.VisitedStoresColumns.CONTENT_URI, values);
                visitTaskInfo.mDbId = Long.parseLong(uri.getPathSegments().get(1));
            }else{
                context.getContentResolver().update(SalesSettings.VisitedStoresColumns.getContentUri(visitTaskInfo.mDbId, false), values, null, null);
            }
            return true;
        }catch(Exception e){
            return false;
        }
    }

    public static boolean saveStoresCheckoutInfo(Context context, VisitTaskInfo visitTaskInfo, double lat, double lng){
        try{
            ContentValues values = new ContentValues();
            values.put(SalesSettings.VisitedStoresColumns.STOREID, visitTaskInfo.id);
            values.put(SalesSettings.VisitedStoresColumns.CHECKOUT_LAT, lat);
            values.put(SalesSettings.VisitedStoresColumns.CHECKOUT_LNG, lng);
            values.put(SalesSettings.VisitedStoresColumns.CHECKOUT_TIME, visitTaskInfo.mCheckoutTime);
            values.put(SalesSettings.VisitedStoresColumns.VISITSTATUS, 1);
            if(Actions.DEBUG){
                Log.e("zhu","checkout id="+visitTaskInfo.mDbId);
            }
            if(visitTaskInfo.mDbId == -1){
                Uri uri = context.getContentResolver().insert(SalesSettings.VisitedStoresColumns.CONTENT_URI, values);
                visitTaskInfo.mDbId = Long.parseLong(uri.getPathSegments().get(1));
            }else{
                context.getContentResolver().update(SalesSettings.VisitedStoresColumns.getContentUri(visitTaskInfo.mDbId, false), values, null, null);
            }
            return true;
        }catch(Exception e){
            return false;
        }
    }

    public static boolean saveStoresClose(Context context, long dbid){
        try{
            ContentValues values = new ContentValues();
            values.put(SalesSettings.VisitedStoresColumns.CLOSE, 1);
            context.getContentResolver().update(SalesSettings.VisitedStoresColumns.getContentUri(dbid, false), values, null, null);
            return true;
        }catch(Exception e){
            return false;
        }
    }

    public static String getDatingTaskActualID(String eid, String cid){
    	SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
    	Date curDate = new Date(System.currentTimeMillis());
    	String str = formatter.format(curDate);
    	return str + eid + cid;
    }

	public static double GetShortDistance(double lon1, double lat1, double lon2,
			double lat2) {
		double ew1, ns1, ew2, ns2;
		double dx, dy, dew;
		double distance;
		// 角度转换为弧度
		ew1 = lon1 * DEF_PI180;
		ns1 = lat1 * DEF_PI180;
		ew2 = lon2 * DEF_PI180;
		ns2 = lat2 * DEF_PI180;
		// 经度差
		dew = ew1 - ew2;
		// 若跨东经和西经180 度，进行调整
		if (dew > DEF_PI)
			dew = DEF_2PI - dew;
		else if (dew < -DEF_PI)
			dew = DEF_2PI + dew;
		dx = DEF_R * Math.cos(ns1) * dew; // 东西方向长度(在纬度圈上的投影长度)
		dy = DEF_R * (ns1 - ns2); // 南北方向长度(在经度圈上的投影长度)
		// 勾股定理求斜边长
		distance = Math.sqrt(dx * dx + dy * dy);
		return distance;
	}

	public static double GetLongDistance(double lon1, double lat1, double lon2,
			double lat2) {
		double ew1, ns1, ew2, ns2;
		double distance;
		// 角度转换为弧度
		ew1 = lon1 * DEF_PI180;
		ns1 = lat1 * DEF_PI180;
		ew2 = lon2 * DEF_PI180;
		ns2 = lat2 * DEF_PI180;
		// 求大圆劣弧与球心所夹的角(弧度)
		distance = Math.sin(ns1) * Math.sin(ns2) + Math.cos(ns1)
				* Math.cos(ns2) * Math.cos(ew1 - ew2);
		// 调整到[-1..1]范围内，避免溢出
		if (distance > 1.0)
			distance = 1.0;
		else if (distance < -1.0)
			distance = -1.0;
		// 求大圆劣弧长度
		distance = DEF_R * Math.acos(distance);
		return distance;
	}

	public static int getVerCode(Context context){
        int verCode = 0;
        try {
            verCode = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionCode;
        } catch (NameNotFoundException e) {
            // TODO Auto-generated catch block
            if(Actions.DEBUG){
            	e.printStackTrace();
            }
        }
        return verCode;
    }

	public static String getVerName(Context context){
        String verName = null;
        try {
            verName = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionName;
        } catch (NameNotFoundException e) {
            // TODO Auto-generated catch block
            if(Actions.DEBUG){
                e.printStackTrace();
            }
        }
        return verName;
    }

	public static boolean canOfflineLogin(Context context){
	    Cursor cursor = null;
	    boolean isCheckin = false;
        boolean isCheckout = false;
        try{
            String where = "storeid = \'" + VisitTaskListActivity.STARTCHECKID + "\' OR storeid = \'"+ VisitTaskListActivity.STOPCHECKID+"\'";
            cursor = context.getContentResolver().query(SalesSettings.VisitedStoresColumns.CONTENT_URI, null, where, null, null);
            int cidindex = cursor.getColumnIndexOrThrow(SalesSettings.VisitedStoresColumns.STOREID);
            int checkindex = cursor.getColumnIndexOrThrow(SalesSettings.VisitedStoresColumns.CHECKIN_TIME);
            while (cursor.moveToNext()) {
                String tid = cursor.getString(cidindex);
                String checkintime = cursor.getString(checkindex);
                if(tid.equals(VisitTaskListActivity.STARTCHECKID) && checkintime != null && checkintime.length() > 1){
                    isCheckin = true;
                }else if(tid.equals(VisitTaskListActivity.STOPCHECKID) && checkintime != null && checkintime.length() > 1){
                    isCheckout = true;
                }
            }
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            if(cursor != null){
                cursor.close();
                cursor = null;
            }
            if(isCheckin && !isCheckout){
                return true;
            }
            return false;
        }
	}

	public static boolean isEndVisit(Context context){
        Cursor cursor = null;
        boolean isCheckin = false;
        boolean isCheckout = false;
        try{
            String where = "storeid = \'" + VisitTaskListActivity.STARTCHECKID + "\' OR storeid = \'"+ VisitTaskListActivity.STOPCHECKID+"\'";
            cursor = context.getContentResolver().query(SalesSettings.VisitedStoresColumns.CONTENT_URI, null, where, null, null);
            int cidindex = cursor.getColumnIndexOrThrow(SalesSettings.VisitedStoresColumns.STOREID);
            int checkindex = cursor.getColumnIndexOrThrow(SalesSettings.VisitedStoresColumns.CHECKIN_TIME);
            while (cursor.moveToNext()) {
                String tid = cursor.getString(cidindex);
                String checkintime = cursor.getString(checkindex);
                if(tid.equals(VisitTaskListActivity.STARTCHECKID) && checkintime != null && checkintime.length() > 1){
                    isCheckin = true;
                }else if(tid.equals(VisitTaskListActivity.STOPCHECKID) && checkintime != null && checkintime.length() > 1){
                    isCheckout = true;
                }
            }
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            if(cursor != null){
                cursor.close();
                cursor = null;
            }
            if(!isCheckin || (isCheckin && isCheckout)){
                return true;
            }
            return false;
        }
    }
}
